import wx
#from wx import Menu, MenuBar

#import matplotlib.backends.backend_wx
#from matplotlib.backends.backend_wx import error_msg_wx

from iplot.mpl.debug import _DEBUG

_DEBUG=5

from iplot.mpl.wx_utils import bind
from iplot.mpl.debug import DEBUG_MSG
from iplot.mpl.units import addUnitsToLine

import os, sys, traceback

class FileMenu(wx.Menu):

    def __init__(self,frame):
        wx.Menu.__init__(self)
        self.frame = frame
        self._init_menu()
        
    filetypes = {
        'xml': 'Matplotlib XML file' ,
        }

    def _init_menu(self):
        """
        This is where you actually build the GUI widgets (called by
        __init__)
        """
        DEBUG_MSG("_init_menu", 1, self)
        frame = self.frame
        
        _FILEMENU_OPEN = wx.NewId()

        self.Append(_FILEMENU_OPEN,"&Open","Open file...")
            
        bind(frame,wx.EVT_MENU,self.open_xml,id=_FILEMENU_OPEN)

    def open_xml(self, event):
        # Fetch the required filename and file type.
        filetypes, exts, filter_index = self._get_imageopen_wildcards()
        default_file = '' # "image." + self.canvas.get_default_filetype()
        dlg = wx.FileDialog(self.frame, "Open file", "", default_file,
                            filetypes,
                            wx.OPEN|wx.CHANGE_DIR)
        dlg.SetFilterIndex(filter_index)
        if dlg.ShowModal() == wx.ID_OK:
            dirname  = dlg.GetDirectory()
            filename = dlg.GetFilename()
            DEBUG_MSG('Open file dir:%s name:%s' % (dirname, filename), 3, self)
            #format = exts[dlg.GetFilterIndex()]
            #basename, ext = os.path.splitext(filename)
            #if ext.startswith('.'):
            #    ext = ext[1:]
            #if ext in ('svg', 'pdf', 'ps', 'eps', 'png') and format!=ext:
            #    #looks like they forgot to set the image type drop
            #    #down, going with the extension.
            #    warnings.warn('extension %s did not match the selected image type %s; going with %s'%(ext, format, ext), stacklevel=0)
            #    format = ext
            try:
                from iplot.mpl.xml2fig import XMLFigure
                
                filename = os.path.join(dirname, filename)
                #print 'aaaaaaaaa',filename
                a = XMLFigure(filename)
                del a
            except Exception:
                #error_msg_wx(str(sys.exc_info()))
                traceback.print_exc(file=sys.stdout)

                
                
    def _get_imageopen_wildcards(self):
        'return the wildcard string for the filesave dialog'
        default_filetype = 'xml'
        filetypes = self.filetypes
        sorted_filetypes = filetypes.items()
        sorted_filetypes.sort()
        wildcards = []
        extensions = []
        filter_index = 0
        for i, (ext,name) in enumerate(sorted_filetypes):
            ext_list = ';'.join(['*.%s' % ext ])
            extensions.append(ext)
            wildcard = '%s (%s)|%s' % (name, ext_list, ext_list)
            if default_filetype == ext:
                filter_index = i
            wildcards.append(wildcard)
        wildcards = '|'.join(wildcards)
        return wildcards, extensions, filter_index
    
class PlotMenu(wx.Menu):

    def __init__(self,frame):
        wx.Menu.__init__(self)
        self.frame = frame
        self._init_menu()

    def _init_menu(self):
        """
        This is where you actually build the GUI widgets (called by
        __init__)
        """
        DEBUG_MSG("_init_menu", 1, self)
        
        frame = self.frame
        
        _PLOTMENU_FILE = wx.NewId()
        _PLOTMENU_MIX = wx.NewId()
        _PLOTMENU_BAR = wx.NewId()
        _PLOTMENU_POLAR = wx.NewId()
        _PLOTMENU_PIE = wx.NewId()
        
        
        self.Append(_PLOTMENU_FILE,'File',"Plot file")
        self.Append(_PLOTMENU_MIX,"Mix","Mix plots")
        self.Append(_PLOTMENU_BAR,"Bar","Plot bars")
        self.Append(_PLOTMENU_POLAR,"Polar","Plot polars")
        self.Append(_PLOTMENU_PIE,"Pie","Plot pie")
        
        DEBUG_MSG("bind()", 1, self)
        bind(frame,wx.EVT_MENU,self._on_plot_mix,id=_PLOTMENU_MIX)
        bind(frame,wx.EVT_MENU,self._on_plot_file,id=_PLOTMENU_FILE)

    def _on_plot_mix(self, event):
        DEBUG_MSG("_on_plot_line()", 1, self)
        frame = self.frame
        frame.mixdlg._refresh()
        # this does not return until the dialog is closed.
        val = frame.mixdlg.ShowModal()
        
        if val == wx.ID_OK:
            pass
        else:
            pass
        
    def _on_plot_file(self,event):
        frame = self.frame
        val = frame.plotfiledlg.ShowModal()
        
        if val == wx.ID_OK:
            #from matplotlib.pyplot import plotfile
            #print "plotfile"
            fname = frame.plotfiledlg.fbb.GetValue()
            args = {
                        'cols': tuple ([ int(val) for val in frame.plotfiledlg.cols.GetValue().split(',') ]),
                        'plotfuncs': frame.plotfiledlg.plotfuncs.GetValue(),
                        'comments': frame.plotfiledlg.comments.GetValue(),
                        'skiprows': int(frame.plotfiledlg.skiprows.GetValue()),
                        'checkrows': int(frame.plotfiledlg.checkrows.GetValue()),
                        'delimiter': str(frame.plotfiledlg.delimiter.GetValue()),
                        'names': frame.plotfiledlg.names.GetValue(),
            
                        'subplots': frame.plotfiledlg.subplots.IsChecked(),
                        'newfig': frame.plotfiledlg.newfig.IsChecked(),
                        }
            
            from matplotlib.pyplot import plotfile
                        
            print "'",args['delimiter'],"'",len(args['delimiter']),type(args['delimiter'])
            
            
            if args['delimiter'] == "\\t" or args['delimiter'] == "tab" :
                args['delimiter'] = '\t'
            
            
            
            if args['names'] == '' or args['names'] == 'None':
                args['names']  = None
                
            if args['plotfuncs'] == '' or args['plotfuncs'] == 'None':
                args['plotfuncs']  = None
                
            
            plotfile(fname,**args)
            #cmd = "matplotlib.pyplot.plotfile('%(fname)s',cols=(%(cols)s), \
            #                plotfuncs=%(plotfuncs)s, \
            #                comments='%(comments)s', \
            #                skiprows=%(skiprows)s, \
            #                checkrows=%(checkrows)s, \
            #                delimiter='%(delimiter)s', \
            #                names=%(names)s, \
            #                subplots=%(subplots)s, \
            #                newfig=%(newfig)s)" % args
                            
            #exec(cmd)
            
            units = frame.plotfiledlg.units.GetValue().split(',')
            units = [str(unit) for unit in units]
            #print units
            from matplotlib.pyplot import gca
            axs = gca()
            axs.xaxis.set_units(units[0])
            axs.yaxis.set_units(units[1])
            for unit in units[1:]:
                #print unit
                for line in axs.lines:
                    addUnitsToLine(line,units[0],unit)
                    #rint line.get_xydata()
                
            
        else:
            pass
        

class MenubarIplot(wx.MenuBar):

    def __init__(self,frame,style=0):
        wx.MenuBar.__init__(self,style)
        self._init_menubar(frame)

    def _init_menubar(self,frame):
        self.filemenu = FileMenu(frame)
        self.plotmenu = PlotMenu(frame)
        
        self.Append(self.filemenu,"&File")
        self.Append(self.plotmenu,"&Plot")


